﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderApp;
using System;
using System.Linq;
using System.Threading.Tasks;
using TodoApi.models;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("api/orders")]
    public class OrdersController : ControllerBase
    {
        private readonly OrderingContext _orderContext;

        public OrdersController(OrderingContext orderContext)
        {
            _orderContext = orderContext;
        }

        [HttpGet("by-id/{id}")]
        public async Task<ActionResult<Order>> GetOrderByOrderIdAsync(int id)
        {
            var order = await _orderContext.Orders
                .Include(o => o.Customer)
                .FirstOrDefaultAsync(o => o.OrderId == id);

            if (order == null)
            {
                return NotFound($"Order with ID {id} not found.");
            }

            return order;
        }

        [HttpGet("by-customer/{customerId}")]
        public ActionResult<Order> GetOrderByCustomerId(string customerId)
        {
            var order = _orderContext.Orders
                .Include(o => o.Customer)
                .FirstOrDefault(o => o.Customer.ID == customerId);

            if (order == null)
            {
                return NotFound($"No orders found for customer ID {customerId}.");
            }

            return order;
        }

        [HttpGet("by-product/{productName}")]
        public ActionResult<Order> GetOrderByProductName(string productName)
        {
            var order = _orderContext.Orders
                .FirstOrDefault(o => o.Details.Any(d => d.GoodsName == productName));

            if (order == null)
            {
                return NotFound($"No orders found for product name {productName}.");
            }

            return order;
        }

        // POST api/orders/add-goods
        [HttpPost("add-goods")]
        public async Task<ActionResult<Goods>> CreateGoodsAsync(Goods goods)
        {
            try
            {
                _orderContext.Goods.Add(goods);
                await _orderContext.SaveChangesAsync();
                return CreatedAtAction(nameof(GetGoods), new { id = goods.Id }, goods);
            }
            catch (Exception ex)
            {
                return BadRequest($"An error occurred: {ex.Message}");
            }
        }

        // POST api/orders/add-customer
        [HttpPost("add-customer")]
        public async Task<ActionResult<Customer>> CreateCustomerAsync(Customer customer)
        {
            try
            {
                _orderContext.Customers.Add(customer);
                await _orderContext.SaveChangesAsync();
                return CreatedAtAction(nameof(GetCustomer), new { id = customer.ID }, customer);
            }
            catch (Exception ex)
            {
                return BadRequest($"An error occurred: {ex.Message}");
            }
        }

        // POST api/orders/add
        [HttpPost("add")]
        public async Task<ActionResult<Order>> CreateOrderAsync(Order order)
        {
            try
            {
                _orderContext.Orders.Add(order);
                await _orderContext.SaveChangesAsync();
                return CreatedAtAction(nameof(GetOrderByOrderIdAsync), new { id = order.OrderId }, order);
            }
            catch (Exception ex)
            {
                return BadRequest($"An error occurred: {ex.Message}");
            }
        }

        [HttpPut("update/{id}")]
        public async Task<IActionResult> UpdateOrderAsync(int id, Order order)
        {
            if (id != order.OrderId)
            {
                return BadRequest("Order ID mismatch.");
            }

            _orderContext.Entry(order).State = EntityState.Modified;

            try
            {
                await _orderContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!OrderExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        [HttpDelete("delete/{id}")]
        public async Task<IActionResult> DeleteOrderAsync(int id)
        {
            if (!OrderExists(id))
            {
                return NotFound();
            }

            var order = await _orderContext.Orders.FindAsync(id);
            _orderContext.Orders.Remove(order);
            await _orderContext.SaveChangesAsync();

            return NoContent();
        }

        private bool OrderExists(int id)
        {
            return _orderContext.Orders.Any(e => e.OrderId == id);
        }
    }
}